package com.mjgy.controller;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.common.utils.R;
import com.mjgy.config.SysConfig;

/**
* @Description: 通用接口
* @author LGC
* @date 2018年9月10日
* @version V1.0
*/
@RestController
@RequestMapping("/common")
public class CommonController {

	private Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private HttpServletRequest request;
	
	/**
	 * 发送短信验证码
	 * 
	 * @param session
	 * @param phone
	 * @return
	 */
	@RequestMapping("/sendVerfiCode")
	public R sendVerifCode(HttpSession session, String phone, int type) {
		// 随机生成验证码
		String verifCode = (int) ((Math.random() * 9 + 1) * 100000) + "";
		
		String product = SysConfig.messProduct;
		String domain = SysConfig.messDomain;
		String appKey = SysConfig.messAppKey;
		String appSecret = SysConfig.messAppSecret;
		String signName = SysConfig.messSignName;
		String templateCode = "";
		String templateParam = "{\"code\":\"" + verifCode + "\"}";

		switch (type) {
		case 1: // 注册
			templateCode = SysConfig.messRegisterCode;
			break;
		case 2: // 绑定手机
			templateCode = SysConfig.messBindPhoneCode;
			break;
		case 3: // 修改密码
			templateCode = SysConfig.messUpdatePassword;
			break;
		default:
			
			break;
		}
		
		try {
			// 初始化acsClient，暂不支持region化
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", appKey, appSecret);
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
			
			IAcsClient acsClient = new DefaultAcsClient(profile);
			
			// 组装请求对象
			SendSmsRequest request = new SendSmsRequest();
			request.setPhoneNumbers(phone);
			request.setSignName(signName);
			request.setTemplateCode(templateCode);
			request.setTemplateParam(templateParam);
			
			SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
			if("OK".equals(sendSmsResponse.getCode())) {
				// 存到session中，后续验证。
				session.setAttribute(phone, verifCode);
				session.setAttribute(phone + "Time", new Date()); // 记录验证码有效时间
				
				R r = R.success("发送成功");
				return r;
			}else{
				return R.error(202, sendSmsResponse.getMessage());
			}
			
			
		} catch (ClientException e) {
			e.printStackTrace();
		}
		
		return R.error();
	}
	
	/**
	 * 上传图片
	 * 
	 * @param file
	 * @return
	 */
	@RequestMapping("/uploadPhoto")
	public R uploadPhoto(@RequestParam("image") MultipartFile file) {
		InputStream inputStream = null;
		try {
			if(!file.isEmpty()) {
				StringBuffer sb = request.getRequestURL();
				String fileName = UUID.randomUUID().toString() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
				inputStream = file.getInputStream();
				File rootPath = new File(ResourceUtils.getURL("classpath:").getPath());
				File imagePath = new File(rootPath.getAbsolutePath(), "static/images");
				Path path = Paths.get(imagePath.getAbsolutePath(), fileName);
				Files.copy(inputStream, path);
				return R.success().put("data", sb.toString().replace("common/uploadPhoto", "") + "images/" + fileName);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(inputStream != null) {
					inputStream.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return R.error();
	}
}
